/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    pair<ListNode*,ListNode*> reverse(ListNode* head,ListNode* tail)
    {
        ListNode* prev = tail -> next;
        ListNode* endd = tail -> next;
        ListNode* hh = head;
        while(head != endd)
        {
            ListNode* now = head;
            head = head -> next;
            now -> next = prev;
            prev = now;
        }
        return {tail,hh};
    }
    ListNode* reverseKGroup(ListNode* head, int k) {
        ListNode* node = new ListNode(0);
        ListNode* tail = head;
        node -> next = head;
        ListNode* prev = node;
        while(head != nullptr)
        {
            tail = prev -> next;
            for(int i = 1; i <= k - 1; i ++)
            {
                if(tail -> next == nullptr) return node -> next;
                tail = tail -> next;
            }
            pair<ListNode*,ListNode*> res = reverse(head,tail);
            head = res.first;
            tail = res.second;
            prev->next = head;
            prev = tail;
            head = tail -> next;
        }
        return node -> next;
    }
};